﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using ASPNETPerformance.App_BusinessLogic.Helpers;
using ASPNETPerformance.App_BusinessLogic.SEO;
using ASPNETPerformance.App_BusinessLogic.Utils;

namespace ASPNETPerformance.App_BusinessLogic.HttpModules {
    public class WebImageHttpModule : IHttpModule {
        private static readonly List<string> _headersToRemove = new List<string> { "X-AspNet-Version", "X-AspNetMvc-Version", "Etag", "Server", };
        private static readonly List<string> _longCacheExtensions = new List<string> { ".png", ".jpg", ".gif", ".ico", };

        public void Init( HttpApplication context ) {
            context.EndRequest += OnRequestEnd;
        }
        public void Dispose() {
        }

        private void OnRequestEnd( object sender, EventArgs e ) {
            var context = HttpContext.Current;
            if( !context.Request.IsLocal && !context.IsDebuggingEnabled ) {
                _headersToRemove.ForEach( h => context.Response.Headers.Remove( h ) );
            }
            var extension = Path.GetExtension( context.Request.Url.AbsolutePath );
            var date = File.GetCreationTime( context.Server.MapPath( context.Request.Url.AbsolutePath ) );
            if( _longCacheExtensions.Contains( extension ) && CommonHelper.GetCookieBool( "IsStaticCacheByImage" ) ) {
                context.Response.CacheControl = "Public";
                context.Response.Cache.SetMaxAge( new TimeSpan( 30, 0, 0, 0, 0 ) );
                context.Response.Expires = 44000; //1月后过期
                SEOHelper.SetConditionalBrowserCache( context, date );
            }
        }
    }
}